<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/28
 * Time: 15:26
 */
declare(strict_types=1);

namespace App\Controller\MchApi;

use App\Exception\XZXValidationException;
use App\Middleware\MchApi\MchJWTAuthMiddleware;
use App\Service\MchAccountService;
use App\Service\MchInfoService;
use App\Service\RateSettleService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Contract\TranslatorInterface;
use App\Constants\XZXResponseCode;
use App\Utils\CustomUtils;

/**
 * Class MchInfoController
 * @package App\Controller
 * @Controller(prefix="/mch/api/mchInfo")
 */
class MchInfoController extends MchBaseController
{
    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchInfoService
     */
    protected $MchInfoService;

    /**
     * @Inject()
     * @var MchAccountService
     */
    protected $MchAccountService;

    /**
     * @Inject()
     * @var RateSettleService
     */
    protected $RateSettleService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale()
    {
        if($this->request->header('locale') == 'en')
        {
            $this->translator->setLocale('en');
        }
    }    

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        
        $param['mchId'] = $ext['mchId'];
        // CustomUtils::xzxDebug($param);
        if($param['id'] != $param['mchId']){
            // throw new XZXValidationException("没有权限");
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
        }        
        return $this->MchInfoService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'                    => 'required|uuid',
                'email'                 => 'sometimes|required|email',
                'code'                  => 'sometimes|required',
                'url'                   => 'sometimes',
                'mchName'               => 'sometimes',
                // 'mobile'                => 'sometimes|regex:/^1[3456789]\d{9}$/',
                'registerCertificateNo' => 'sometimes',
                'bankAccountName'       => 'sometimes',
                'bankAccountNo'         => 'sometimes',
                'bankOpenBankNo'        => 'sometimes',
                'registerAddress'       => 'sometimes',
                'corporation'           => 'sometimes',
                'phone'                 => 'sometimes',
                'registerCert'          => 'sometimes',
                'companyPolice'         => 'sometimes',
                'companyAgentPassport'  => 'sometimes',
                'corporationCert'       => 'sometimes',
                'corporationDecision'   => 'sometimes',
                'nnc'                   => 'sometimes',
                'registerAddressCert'   => 'sometimes',
                'bankAccountNoCert'     => 'sometimes',
                'legalPersonCert'       => 'sometimes',
                'officeCert'            => 'sometimes',
                'fieldStatus'           => 'sometimes',
                'isReAuth'              => 'sometimes|integer|max:1|min:0',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];
        if($param['id'] != $param['mchId']){
            // throw new XZXValidationException("没有权限");
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
        } 
        unset($param['isAgree']);
        $param['source'] = 1;
        $param['createBy'] = $param['email'];
        CustomUtils::xzxDebug($param);
        return $this->MchInfoService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "register")
     */
    public function register(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'email'                        => 'required|email',
                'code'                         => 'required',
                'mchName'                      => 'required',
                'url'                          => 'required',
                // 'mobile'                       => 'required|regex:/^[0-9]*$/',
                'registerCertificateNo'        => 'required',
                'bankAccountName'              => 'required',
                'bankAccountNo'                => 'required',
                'bankOpenBankNo'               => 'required',
                'registerAddress'              => 'required',
                'corporation'                  => 'required',
                'phone'                        => 'required',
                'registerCert'                 => 'required',
                'companyPolice'                => 'required',
                'companyAgentPassport'         => 'required',
                'corporationCert'              => 'required',
                'corporationDecision'          => 'required',
                'nnc'                          => 'required',
                'registerAddressCert'          => 'required',
                'bankAccountNoCert'            => 'required',
                'legalPersonCert'              => 'required',
                'officeCert'                   => 'required',
                'fieldStatus'                  => 'required',
                "isAgree"                      => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if (!$param['isAgree']) {
            // throw new XZXValidationException('请同意协议再注册');
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::MCH_REG_IS_AGREE));
        }
        if (substr(strtolower($param['url']), 0, 4) == 'http') {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::MCH_REG_MCH_URL));
        }
        unset($param['isAgree']);

        $param['source'] = 1;
        $param['createBy'] = $param['email'];
        
        return $this->MchInfoService->add($param);
    }

    /**
     * 查看账户
     * @PostMapping(path = "account")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function account(RequestInterface $request)
    {
        $this->setlocale();

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];
        return $this->MchAccountService->getForMch($param);
    }

    /**
     * 结算费率
     * @PostMapping(path = "rateSettle")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function rateSettle(RequestInterface $request)
    {
        $this->setlocale();

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];
        return $this->RateSettleService->getForMch($param);
    }

    /**
     * config
     * @PostMapping(path = "getConfig")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function getConfig(RequestInterface $request)
    {
        $this->setlocale();

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];
        return $this->MchInfoService->getConfig($param);
    }


    /**
     * changeEmail
     * @PostMapping(path = "changeRegEmail")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function changeRegEmail(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                // 'id'                    => 'required|uuid',
                'email'                 => 'required|email',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];
        // if($param['id'] != $param['mchId']){
        //     // throw new XZXValidationException("没有权限");
        //     throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
        // } 
        $param['uid']      =  $ext['uid']; 
        $param['source'] = 1;
        $param['createBy'] = $param['email'];
        
        CustomUtils::xzxDebug($param);
        return $this->MchInfoService->changeRegEmail($param);
    }    

}